﻿/*
*类名：SubscribeEventDeal
*归属：QinMing.Weixin.EventHandlerSubscribe命名空间
*用途：处理微信用户发给公众号的关注公众号事件，并给予微信用户处理结果通知，通过微信服务器转发给微信用户
*作者：乱世刀疤
*日期：2020.05.02
*/

using System;
using System.Web;
using System.Xml;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using QinMing.Config;
using QinMing.Tools;
using QinMing.Tools.DB;
using QinMing.Weixin.ReturnContent;
using QinMing.WeixinUserInfo;
using QinMing.WeixinPayPayment;

namespace QinMing.Weixin.EventHandlerSubscribe
{
	//事件消息处理：关注公众号
    public class SubscribeEventDeal :System.Web.UI.Page
    {

		public string DealResult(string weixinXML)
        {
            string content = DealSubscribe(weixinXML);  
            return content;
        }

        public string DealSubscribe(string weixinXML)
        {
            string content1="";
            string strresponse = "";
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(weixinXML);
            XmlNodeList list = doc.GetElementsByTagName("xml");
            XmlNode xn = list[0];
            string FromUserName = xn.SelectSingleNode("//FromUserName").InnerText;   //关注用户的加密后openid
            string ToUserName = xn.SelectSingleNode("//ToUserName").InnerText;       //公众微信号原始ID
            string MsgType=xn.SelectSingleNode("//MsgType").InnerText;
            string Event=xn.SelectSingleNode("//Event").InnerText;
			string EventKey = xn.SelectSingleNode("//EventKey").InnerText;
			ReturnMsg rm = new ReturnMsg();
            
			if(String.IsNullOrEmpty(EventKey))   //常规关注
			{
				DealJoin(FromUserName);
                SaveEventCommon(FromUserName, ToUserName);				
				content1 = "欢迎您：\n\n"
					+ "[玫瑰]超值优惠券[玫瑰]\n"
					+ "肯德基、麦当劳、汉堡王、德克士、必胜客、星巴克、Coco、猫眼、美团外卖、饿了么、滴滴等上百家全国知名连锁商家4折起优惠券，随时买随时用，无需加会员和预充值，全国门店通用！\n\n"
					+ "<a href='xxxxxxxxxxx' >点击这里购买！</a>"
					+ "\n\n"
					+ "<a href='xxxxxxxxxxx' >点击这里购买！！</a>"
					+ "\n\n"
					+ "<a href='xxxxxxxxxxx' >点击这里购买！！！</a>"
					+ "\n\n"
					+ "您也可以通过菜单”超值优惠券“进入购买页面，总有惊喜在等您哦！";
				strresponse = rm.ReturnText(FromUserName, ToUserName, content1); 
				
				//给管理员发送新粉丝关注通知
				QinMing.WeixinTemplateMessage.SendTemplateMessage.SendRemindMsg("管理员openid", "新粉丝关注提醒(来源:普通关注)" + FromUserName, "http://www.yourweb.com/Weixin/DisplayOneUser.aspx?open_id=" + FromUserName);  //告知管理员有新粉丝关注
			}	
			else    //扫描带参数的二维码关注，一人一码、一店一码
			{
				
				string tmpEventKey = EventKey.Substring(EventKey.LastIndexOf("_") + 1);
				string ticket = xn.SelectSingleNode("//Ticket").InnerText;
				SaveEventScan(FromUserName, ToUserName, tmpEventKey, ticket);
				if(tmpEventKey == "10")   //某个指定的带参数二维码scene_id
				{
					   
				}
				else
				{
				    strresponse = ScanWithQrCodeNew(FromUserName, ToUserName, tmpEventKey); 
				}

			}
			
			return strresponse;
        }
		
        //记录粉丝关注公众号时的相关信息
		public void DealJoin(string FromUserName)
        {
            SqlConnection conn = new SqlConnection(QinMingConfig.DatabaseConnStr);
            conn.Open();
            SqlCommand cmd = new SqlCommand();
			SqlDataReader dr;
            cmd.Connection = conn;
            cmd.CommandText = "insert into weixin_join_log (open_id,join_time,remove_flag) values('" + FromUserName + "',getdate(),0)";
            cmd.ExecuteScalar();
			
			cmd.CommandText = "select * from weixin_user_info where open_id ='" + FromUserName + "' ";
			dr = cmd.ExecuteReader();
            if(dr.Read())
			{
				dr.Close();
				cmd.CommandText = "update weixin_user_info set remove_flag='已关注' where open_id='" + FromUserName + "'";
                cmd.ExecuteScalar();//新增粉丝如曾关注过，取关后重新关注的，变更状态
			}
			else
			{
				dr.Close();
				cmd.CommandText = "insert into weixin_user_info (open_id,remove_flag,personal_score,join_time) values('" + FromUserName + "','已关注',0,getdate())";
                cmd.ExecuteScalar();//新增粉丝如曾未关注过，增加粉丝记录
				
				//微信用户首次关注公众号时，发送一个随机红包。
				SendNewUserRedPacket(FromUserName);
			}
			
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
                conn.Dispose();
            }			

            QinMingWeixinUserInfo wui=new QinMingWeixinUserInfo();
            wui.UpdateUserInfo(FromUserName);    //获取用户信息并更新weixin_user_info表
        }
		
        /*给一个新关注公众号的粉丝发红包，仅限首次关注，取消关注后再次关注时没有此红包*/
		public void SendNewUserRedPacket(string open_id)
        {
            Random r = new Random();
			string ran1 = r.Next(1000, 9999).ToString();
			string ran2 = r.Next(100, 110).ToString();
			string out_trade_no = QinMingConfig.Weixin_MchId + DateTime.Now.ToString("yyyyMMddHHmmss") + ran1;
			QinMingWeixinPayPayment.SendRedPackOne("降价联盟", "新粉福利", open_id, ran2, "新粉关注红包", "", out_trade_no);
        }
		
		//用户扫描带参数的二维码时处理动作
		public string ScanWithQrCodeNew(string FromUserName, string ToUserName, string EventKey)
        {
            string strresponse = "";
			ReturnMsg rm = new ReturnMsg();
			string guishu_mobile = "";
			string guishu_name = "";
            string guishu_type = "";
			string scan_title = "";
			string scan_title_sub = "";
			string scan_image_url = "";
			string scan_redirect_url = "";
			string r_red_packet_min = "";
			string r_red_packet_max = "";

            SqlConnection conn = new SqlConnection(QinMingConfig.DatabaseConnStr);
            conn.Open();
            SqlCommand cmd = new SqlCommand();
			SqlDataReader dr;
            cmd.Connection = conn;
			
            cmd.CommandText = "select * from weixin_qrcode_ticket where scene_id=" + EventKey + " ";
            dr = cmd.ExecuteReader();
			if(dr.Read())
			{
                if(dr["scan_type"].ToString() == "优惠券")
				{
					guishu_mobile = dr["user_id"].ToString();
					guishu_name = dr["user_name"].ToString();
					guishu_type = dr["scan_type"].ToString();
					scan_title = dr["scan_title"].ToString();
					scan_title_sub = dr["scan_title_sub"].ToString();
					scan_image_url = dr["scan_image_url"].ToString();
					scan_redirect_url = dr["scan_redirect_url"].ToString();
					r_red_packet_min = dr["r_red_packet_min"].ToString();
					r_red_packet_max = dr["r_red_packet_max"].ToString();
					Random r = new Random();
					int RandomRedpack = r.Next(int.Parse(r_red_packet_min), int.Parse(r_red_packet_max));

					strresponse = rm.ReturnText(FromUserName,ToUserName,"欢迎您：[咖啡]\n\n"
						+ "[玫瑰]超值优惠券[玫瑰]\n"
						+ "肯德基、麦当劳、汉堡王、德克士、必胜客、星巴克、Coco、猫眼、美团外卖、饿了么、滴滴等上百家全国知名连锁商家4折起优惠券，随时买随时用，无需加会员和预充值，全国门店通用！\n\n"
						+ "<a href='xxxxxxxxxxx' >点击这里购买！</a>"
                        + "\n\n"
						+ "<a href='xxxxxxxxxxx' >点击这里购买！！</a>"
                        + "\n\n"
						+ "<a href='xxxxxxxxxxx' >点击这里购买！！！</a>"
                        + "\n\n"
						+ "您也可以通过菜单”超值优惠券“进入购买页面，总有惊喜在等您哦！");
					
					dr.Close();
					
					//给推荐的合伙人发红包，用生成红包记录自行提现方式;非首次扫码关注公众号，不发推荐红包包
		            /**/
					if(int.Parse(QinMingToolsDB.SearchOneField("select count(*) r_m from weixin_user_info where open_id= '" + FromUserName + "'","r_m")) >= 1 )
					{
						//如果用户表中已经存在微信用户openid，则表示非首次关注，不给推荐人发红包
					}
					else
					{
						//如果用户表中没有微信用户openid，则表示首次关注，给推荐人发红包；在推荐红包表中追加记录，需推荐人自行提现
						string test = CreateScanQrCodeRedpack(FromUserName, guishu_mobile, guishu_type, RandomRedpack.ToString());
					}
					
					DealJoin(FromUserName);

					//如果是带参数二维码扫码关注，更新新粉丝扫码推荐人归属信息。
					cmd.CommandText = "update weixin_user_info set guishu_mobile='" + guishu_mobile + "',guishu_type ='" + guishu_type + "' where remove_flag='已关注' and open_id='" + FromUserName + "' ";
					cmd.ExecuteScalar();
					
					//告知管理员有新粉丝扫码关注
					QinMing.WeixinTemplateMessage.SendTemplateMessage.SendRemindMsg("管理员openid", "新粉丝关注提醒(来源:" + guishu_name + ")"  + FromUserName, "http://www.yourweb.com/Weixin/DisplayOneUser.aspx?open_id=" + FromUserName);  
					
					//插入带参数二维码被扫码的记录
					cmd.CommandText = "insert into weixin_ad_image_read_log (share_qrcode_id,read_open_id,read_time) values (" 
					    + EventKey + ",'" + FromUserName + "',getdate())"; //EventKey对应的是weixin_qrcode_ticket表中的scene_id，二维码分配关系
					cmd.ExecuteScalar();
				}
				else
				{
                     dr.Close();
				}
				
				if (conn.State == ConnectionState.Open)
				{
					conn.Close();
					conn.Dispose();
				}
			}
			
			return strresponse;
		}
		
		//微信用户通过扫描带参数二维码关注公众号时，给推荐扫码的人追加一条红包记录
		public string CreateScanQrCodeRedpack(string FromUserName, string guishu_mobile, string guishu_type, string redpack_fee)
        {
			string order_id = QinMingToolsDB.SearchOneField("select isnull(max(order_id),0)+1 r_num from weixin_redpack_log_yhq_spread","r_num");
			string fromopenid = QinMingToolsDB.SearchOneField("select open_id from weixin_bind_mobile_all where mobile = '"+ guishu_mobile +"'","open_id");
			string scene_id = QinMingToolsDB.SearchOneField("select top 1 * from weixin_qrcode_ticket where user_id = '"+ guishu_mobile +"' and scan_type = '"+ guishu_type +"'","scene_id");
			string fromname = QinMingToolsDB.SearchOneField("select top 1 * from weixin_qrcode_ticket where user_id = '"+ guishu_mobile +"' and scan_type = '"+ guishu_type +"'","user_name");
			string strsql = "insert into weixin_redpack_log_yhq_spread(order_id,open_id,gen_time,redpack_class,redpack_fee,scene_id,from_user_id,from_user_name,from_open_id,remark,out_trade_no) \n"+
							"values("+ order_id +",'"+ FromUserName +"',getdate(),'优惠券推荐新粉红包',"+ redpack_fee +",'"+ scene_id +"','"+ guishu_mobile +"','"+ fromname +"','"+ fromopenid +"','','')\n";
			QinMingToolsDB.InsertTable(strsql);

			return "2"; //用户
        }
		
		//保存普通关注事件信息。
        public void SaveEventCommon(string FromUserName, string ToUserName)
        {
            SqlConnection conn = new SqlConnection(QinMingConfig.DatabaseConnStr);
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = "insert into weixin_recv_event (msg_type,event_type,open_id,gh_id,recv_time) "
			    + "values ('event','subscribe','" + FromUserName + "','" + ToUserName + "',getdate()) ";
            QinMingTools.WriteLog("sql语句：", cmd.CommandText);
			cmd.ExecuteScalar();
      
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
                conn.Dispose();
            }
        }
		
		//保存扫描带参数二维码事件信息。
        public void SaveEventScan(string FromUserName, string ToUserName,string EventKey, string Ticket)
        {
            SqlConnection conn = new SqlConnection(QinMingConfig.DatabaseConnStr);
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = "insert into weixin_recv_event (msg_type,event_type,open_id,gh_id,recv_time,event_key,ticket) "
			    + "values ('event','subscribe','" + FromUserName + "','" + ToUserName + "',getdate(),'" + EventKey + "','" + Ticket + "') ";
            QinMingTools.WriteLog("sql语句：", cmd.CommandText);
			cmd.ExecuteScalar();
      
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
                conn.Dispose();
            }
        }
		
    }
}